package com.yuda.tools.mq.controller;

import cn.hutool.core.io.file.FileAppender;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.aliyun.mns.client.CloudAccount;
import com.aliyun.mns.client.CloudQueue;
import com.aliyun.mns.client.MNSClient;
import com.aliyun.mns.model.Message;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.io.File;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicLong;
import java.util.concurrent.atomic.AtomicReference;

@Controller
public class MSNAliYunRtc {


    private static final int mQThreadNum = 10;

    private final ExecutorService executorService = Executors.newFixedThreadPool(mQThreadNum);

    private final CloudAccount account = new CloudAccount("LTAIssc9TCX1Pe0Q", "oCmWCl1vClDXhdyR9KWPe90CqJcl6P",
            "http://1098879781219972.mns.cn-shanghai.aliyuncs.com"); //.cn-beijing-internal.aliyuncs.com

    //this client need only initialize once
    private final MNSClient client = account.getMNSClient();

    private CloudQueue queue = null;

    AtomicLong atomicLong = new AtomicLong(0);

    private final AtomicReference<Short> powerSupply = new AtomicReference<>(null);
    List<String> list = Collections.synchronizedList(new ArrayList<>());

    FileAppender appender = new FileAppender(new File("E:\\record.txt"), 16, true);

    @ResponseBody
    @RequestMapping("/msnStartRtc")
    public void receiver() {
        try {
            //防止一下开了若干个任务。
            if (powerSupply.get() == null) {
                queue = client.getQueueRef("record-callback-queue");
                //先用一个线程去探测
                executorService.execute(() -> {
                    for (int i = 0; i < Integer.MAX_VALUE; i++) {
                        Message message = queue.peekMessage();
                        if (message != null && message.getMessageId() != null) {
                            //取原来的值看看是不是1 ，如果是1不需要设置
                            Short aShort = powerSupply.get();
                            if (null == aShort || aShort == 0) {
                                System.out.println("任务状态为： 开启");
                                powerSupply.set((short) 1);
                                //通知线程执行
                                executorService.execute(this::executorTask);
                            }
                        } else {
                            powerSupply.set((short) 0);
                            System.out.println("任务状态为： 关闭");
                        }
                        try {
                            TimeUnit.SECONDS.sleep(2);
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    }
                });
            } else {
                System.out.println("有任务正在运行中...");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void executorTask() {
        CountDownLatch countDownLatch = new CountDownLatch(1);
        for (int j = 0; j < 1; j++) {
            executorService.execute(() -> {
                while (powerSupply.get() > 0) {
                    Message popMsg = queue.popMessage();
                    if (popMsg != null) {
                        System.out.println(atomicLong.getAndIncrement());
                        try {
                            String messageBodyAsRawString = popMsg.getMessageBodyAsString();
                            JSONObject jsonObject = JSON.parseObject(messageBodyAsRawString);
                            String url = jsonObject.getString("Url");

                            System.err.println(url);
                            if (url.contains("2021-09-04") && url.contains("d97d9s")) {
                                list.add(url);
                                appender.append(url);
                            }
//                            if (update == 1) {
//                                queue.deleteMessage(popMsg.getReceiptHandle());
//                            }
                        } catch (Exception e) {
                            e.printStackTrace();
                        }

                    }
                }
                countDownLatch.countDown();
            });
        }
        try {
            countDownLatch.await();
            powerSupply.set((short) 0);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

}
